package com.jiaquyun.jcyx.main.goods

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebViewClient
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.entity.CartAction
import com.jiaquyun.jcyx.entity.GoodsDetails
import com.jiaquyun.jcyx.main.goods.adapter.GoodsDetailsImageAdapter
import com.jiaquyun.jcyx.jetpack.mode.GoodsViewModel
import com.jiaquyun.jcyx.main.MainActivity
import com.jiaquyun.jcyx.utils.SpanUtils
import com.jiaquyun.jcyx.utils.WebViewUtils
import com.module.lemlin.LoadingDialog
import com.module.lemlin.http.HttpResponseBody
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeActivity
import com.youth.banner.Banner
import com.youth.banner.indicator.RectangleIndicator
import kotlinx.android.synthetic.main.activity_goods_details.*


class GoodsDetailsActivity : OwnerViewModeActivity<GoodsViewModel>() {

    companion object {
        const val KEY_GOODS_ID = "KEY_GOODS_ID"
    }

    private val mGoodsId: Int
        get() = intent?.extras?.getInt(KEY_GOODS_ID, (0)) ?: 0

    override fun viewModel(): GoodsViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_goods_details

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, view = flGoodsDetailsBar)
    }

    override fun initView() {

        ivAppBack.setOnClickListener { finish() }

        webGoodsDetailsBody.webViewClient = WebViewClient()
        webGoodsDetailsBody.settings.apply {
            //支持缩放，默认为true。
            setSupportZoom(false)
            //调整图片至适合webview的大小
            useWideViewPort = true
            // 缩放至屏幕的大小
            loadWithOverviewMode = true
            //设置默认编码
            defaultTextEncodingName = "utf-8"
            //设置自动加载图片
            loadsImagesAutomatically = true
            //允许访问文件
            allowFileAccess = true
            //开启javascript
            javaScriptEnabled = true
            //支持通过JS打开新窗口
            javaScriptCanOpenWindowsAutomatically = true
            //支持内容重新布局
            layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
            //关闭webview中缓存
            cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
        }

        tvGoodsDetailsAdd.setOnClickListener {
            val details = viewModel.goodsDetailsLiveData.value
                ?.data?.data ?: return@setOnClickListener
            val num: Int = details.cart_num + 1
            viewModel.cartAdd1(details.id, num)
        }

        tvGoodsDetailsPlus.setOnClickListener {
            val details = viewModel.goodsDetailsLiveData.value
                ?.data?.data ?: return@setOnClickListener
            val num: Int = details.cart_num + 1
            viewModel.cartChangeNum1(details.id, details.cart_id, num)
        }
        tvGoodsDetailsReduce.setOnClickListener {
            val details = viewModel.goodsDetailsLiveData.value
                ?.data?.data ?: return@setOnClickListener
            val num: Int = details.cart_num - 1
            if (num == 0) {
                viewModel.cartRemove(details.id, details.cart_id)
            } else {
                viewModel.cartChangeNum1(details.id, details.cart_id, num)
            }
        }

        tvGoodsDetailsCollect.setOnClickListener {
            viewModel.goodsCollect(mGoodsId)
        }

        tvGoodsDetailsCart.setOnClickListener {
            MainActivity.open(action = 2)
        }
    }

    override fun initData() {
        viewModel.goodsInfo(mGoodsId)
    }

    override fun initViewMode() {
        viewModel.goodsDetailsLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val data = response.data?.data
                ?: return@Observer
            fillData(data)
        })

        //监听购物车添加
        viewModel.cartAdd1LiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })

        //监听购物车加减
        viewModel.cartChangeNum1LiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })

        //监听购物车删除
        viewModel.cartDelete1LiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.status.desc)
            }
        })

        //商品收藏
        viewModel.goodsCollectLiveData.observe(this as LifecycleOwner, { response ->
            //responseStatus(response)
            if (response.status != Status.SUCCESS)
                return@observe
            toast(response.data?.msg)
            val top = if (viewModel.isCollect) {
                resources.getDrawable(R.mipmap.ic_4795)
            } else {
                resources.getDrawable(R.mipmap.ic_4794)
            }
            tvGoodsDetailsCollect.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null)
        })
    }


    override fun onEventMainThread(any: Any) {
        if (any !is CartAction)
            return
        val details = viewModel.goodsDetailsLiveData.value
            ?.data?.data ?: return
        details.apply {
            details.cart_id = any.cartId
            details.cart_num = any.goodsNum
        }
        tvGoodsDetailsAdd.visibility =
            if (details.cart_num > 0) View.GONE else View.VISIBLE
        tvGoodsDetailsNum.text = details.cart_num.toString()
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private fun fillData(gd: GoodsDetails) {

        banGoodsDetailsImage.apply {
            indicator = RectangleIndicator(context)
            setIntercept(false)
        }.setOrientation(Banner.HORIZONTAL).setUserInputEnabled(true)
            .adapter = GoodsDetailsImageAdapter().apply {
            setDatas(gd.images)
        }

        tvGoodsDetailsPrice.text =
            SpanUtils.setMoneySymbol(gd.guidance_price, gd.price, 0.8f, 1f)
        tvGoodsDetailsName.text = gd.goods_name
        WebViewUtils.loadFullScreenHtml(webGoodsDetailsBody, gd.goods_content)
        tvGoodsDetailsAdd.visibility = if (gd.cart_num > 0) View.GONE else View.VISIBLE
        tvGoodsDetailsNum.text = gd.cart_num.toString()

        val top = if (gd.is_collect) {
            resources.getDrawable(R.mipmap.ic_4795)
        } else {
            resources.getDrawable(R.mipmap.ic_4794)
        }
        tvGoodsDetailsCollect.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null)

        viewModel.isCollect = gd.is_collect
    }

    private fun responseStatus(response: HttpResponseBody<*>) {
        when (response.status) {
            Status.START -> {
                LoadingDialog.show(this as Context, resId = R.layout.dialog_load_style_1)
            }
            Status.FAILURE -> {
                LoadingDialog.dismiss()
                toast(response.error?.msg)
            }
            Status.SUCCESS -> {
                LoadingDialog.dismiss()
            }
        }
    }
}

